#生成中医会诊单
import os
import json
import time
import random
import string
from docx import Document
import tkinter as tk
from tkinter.simpledialog import askstring
import pyperclip


def cn_datetime(date_str):
    date_struc = time.strptime(date_str, "%Y.%m.%d")
    start_time = time.strftime("%Y{}%m{}%d{} {}", date_struc).format("年","月", "日", "9:00")
    arrivel_time = time.strftime("%Y{}%m{}%d{} {}", date_struc).format("年","月", "日", "9:30")
    return {
        "start_time":start_time,
        "arrivel_time":arrivel_time,
    }

def fill_word(text_info, date_str, consult_content):
    cn_datetime_f = cn_datetime(date_str)
    d = Document('.\\mydocx\\中医会诊单.docx')

    # 获取word文档内的表格列表
    t = d.tables
    # 第一个表格为病人基本信息，包括姓名、性别、年龄
    t1 = t[0]

    info_0 = "姓名：%s       性别：%s       年龄：%s    床号：%s    住院号：%s" % (
        text_info["姓名"],
        text_info["性别"],
        text_info["年龄"],
        text_info["床号"],
        text_info["住院号"],
    )
    run = t1.cell(0, 0).paragraphs[0].add_run(info_0)
    run.font.name = '宋体'
    run.font.size = 140000

    run = t1.cell(2, -1).paragraphs[0].add_run(cn_datetime_f['start_time'])
    run.font.name = '宋体'
    run.font.size = 140000
    info_bref =consult_content["病史"]
    run = t1.cell(4, 0).paragraphs[0].add_run(info_bref)
    run.font.name = '宋体'
    run.font.size = 140000

    run = t1.cell(6, 0).paragraphs[0].add_run(text_info["诊断"])
    run.font.name = '宋体'
    run.font.size = 140000

    run = t1.cell(11, -1).paragraphs[0].add_run(cn_datetime_f['arrivel_time'])
    run.font.name = '宋体'
    run.font.size = 140000

    run = t1.cell(12, 0).paragraphs[0].add_run(consult_content["总结"])
    run.font.name = '宋体'
    run.font.size = 140000
    run = t1.cell(14, 0).paragraphs[0].add_run(consult_content["意见"])
    run.font.name = '宋体'
    run.font.size = 140000

    random_file_name1 = ''.join(
        random.sample(string.ascii_letters + string.digits, 4))
    if not os.path.exists('中医会诊'):
        os.mkdir('中医会诊')
    
    d.save('.\\中医会诊\\%s_%s_%s.docx' % (text_info["姓名"], date_str, random_file_name1))

    os.startfile(os.path.abspath('.\\中医会诊\\%s_%s_%s.docx' % (text_info["姓名"], date_str, random_file_name1)))

class ZYHZ(tk.Toplevel):
    def __init__(self, text_info):
        with open('.\\myjson\\中医会诊.json', 'r', encoding='utf-8') as f:
            info = json.load(f)
        self.info = info
        self.text_info = text_info
        super().__init__()
        self.wm_attributes('-topmost', 1)

        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 600
        wh = 800
        self.geometry("%dx%d+%d+%d" % (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.iconphoto(False, tk.PhotoImage(file='title.png'))
        self.title('中医会诊 01527')

        self.flag = tk.StringVar()
        

        self.time_ = tk.StringVar()
        self.time_.set(time.strftime('%Y.%m.%d', time.localtime()))
        radio_frame = tk.Frame(self)
        radio_frame.grid()
        row_idx = 1
        col_idx = 0
        for k,v in info.items():
            
            tk.Radiobutton(radio_frame,
                        variable=self.flag,
                        text=k,
                        value=v,
                        command=self.clc).grid(row=row_idx,
                                                      column=col_idx,
                                                      sticky="w")
            col_idx += 1
            if col_idx > 3:
                row_idx += 1
                col_idx = 0
        self.flag.set("zyhz")
        tk.Label(self, text=f"会诊时间").grid(pady=5)
        tk.Entry(self, textvariable=self.time_).grid(pady=5)

        tk.Label(self, text="病史").grid(pady=5)
        self.text_1 = tk.Text(self, height=5)
        self.text_1.insert(1.0, f'{text_info["病人简介"]} 以“{text_info["主诉"]}”为主诉入院 查体：{text_info["入院体检"]}')
        self.text_1.grid(pady=5)
        tk.Label(self, text="总结").grid(pady=5)
        self.text_2 = tk.Text(self,height=5 )
        self.text_2.grid(pady=5)
        tk.Label(self, text="意见").grid(pady=5)
        self.text_3 = tk.Text(self,height=5 )
        self.text_3.grid(pady=5)

        btn_frame = tk.Frame(self)
        btn_frame.grid(pady=10)
        btn_ok = tk.Button(btn_frame,
                           text='打印会诊单',
                           width=12,
                           height=1,
                           activebackground='grey',
                           relief='groove')
        btn_ok.bind('<ButtonRelease-1>', self.submit)
        btn_ok.grid(row=1, column=0,)
        btn_copy = tk.Button(btn_frame,
                           text='复制会诊记录',
                           width=12,
                           height=1,
                           activebackground='grey',
                           relief='groove')
        btn_copy.bind('<ButtonRelease-1>', self.copy_it)
        btn_copy.grid(row=1, column=1)
        btn_add = tk.Button(btn_frame,
                               text='添加',
                               command=self.add_new,
                               width=12,
                               height=1,
                               activebackground='grey',
                               relief='groove')
        btn_add.grid(row=2, column=0)
        btn_cancel = tk.Button(btn_frame,
                               text='取消',
                               command=self.cancel,
                               width=12,
                               height=1,
                               activebackground='grey',
                               relief='groove')
        btn_cancel.grid(row=2, column=1)

    def add_new(self):
        flag = True
        hint = '请输入'
        while flag:

            name = askstring(hint,'辩证名称',)
            
            if not self.info.get(name, 0):
                flag = False
            else:
                hint = '名称已存在，请重输！'
        content = f"{self.text_2.get(1.0, tk.END)}zyhz{self.text_3.get(1.0, tk.END)}"
        self.info[name] = content
        with open('.\\myjson\\中医会诊.json', 'w', encoding='utf-8') as w:
            json.dump(self.info, w, ensure_ascii=False)
    def cancel(self):

        self.destroy()

    def submit(self, event):
        
        fill = {'病史':self.text_1.get(1.0, tk.END), '总结': self.text_2.get(1.0, tk.END), '意见': self.text_3.get(1.0, tk.END)}
        fill_word(self.text_info, self.time_.get(), fill)

    def copy_it(self, event):
        result = f'患者姓名：{self.text_info["姓名"]}，性别：{self.text_info["性别"]}，年龄：{self.text_info["年龄"]}。目前诊断：{self.text_info["诊断"]} 申请会诊目的：辨证施治，会诊申请时间：{self.time_.get()} 9：00，请中医儿科赵峥主任医师会诊，会诊医师到达时间：{self.time_.get()} 9：30。会诊简要经过：赵峥主任医师床旁查看患儿、详细询问病史并做体格检查。{self.text_2.get(1.0, tk.END)}{self.text_3.get(1.0, tk.END)} 会诊意见执行情况：已执行。'
        pyperclip.copy(result)

    def clc(self):
        flag = self.flag.get().split('zyhz')
        self.text_2.delete(1.0, tk.END)
        self.text_3.delete(1.0, tk.END)
        self.text_2.insert(1.0, flag[0])
        self.text_3.insert(1.0, flag[1])

if __name__ == "__main__":
    
    app = ZYHZ({'病房': '儿童消化心血管科', '床号': 'W13XC-01', '姓名': '李依诺', '性别': '女', '住院号': '22114787', '入院日期': '2022.08.28', '主诉': '发热3天', '医师': '陈白璐', '诊断': '发热原因待查：肺部感染？颅内感染？呼吸道感染？', '现病史': '3天前患儿无明显诱因出现发热、热型不规律，热峰38.5℃，无咳嗽、气喘、呼吸困难、寒颤等，无皮疹，否认异物吸入，给予口服退热药物应用效差，患儿体温易反复，今为求进一步治疗来我院，门诊以“呼吸道感染”为诊断收住院。发病来，患儿神志清，精神一般，夜内入眠后多汗，近来食欲不佳，大小便基本正常。近期患儿体重无明显变化。', 'TPRBP': 'T：36.8℃ P：124次/分 R：24次/分 BP：未测mmHg W：10kg', '入院体检': '神志清，精神一般，呼吸平稳，口唇发绀，咽腔充血，颈软，双肺呼吸音粗，无啰音，心前区无隆起，心率124次/分，律齐，心音有力，心前区未闻及病理性杂音，腹软，未见胃肠型及胃肠蠕动波，肝脾肋下未触及，肠鸣音5次/分，四肢末梢暖，双下肢无水肿，双侧巴氏征阴性。', '入院化验单': '（2022.08.28，我院门诊）新冠肺炎核酸：阴性。', '病人简介': '李依诺，女，1岁。', '入院情况(出院记录)': '李依诺，女，1岁。 以“发热3天”入院。体格检查：T：36.8℃ P：124次/分 R：24次/分 BP：未测mmHg W：10kg，神志清，精神一般，呼吸平稳，口唇无发绀，咽腔充血，颈软，双肺呼吸音粗，无啰音，心前区无隆起，心率124次/分，律齐，心音有力，心前区未闻及病理性杂音，腹软，未见胃肠型及胃肠蠕动波，肝脾肋下未触及，肠鸣音5次/分，四肢末梢暖，双下肢无水肿，双侧巴氏征阴性。', '病例特点': '1岁患儿，病史3天，反复发热为主要表现，口服药物应用效差，', })
    app.mainloop()